class MainController < ApplicationController
  #before_filter "authenticate_#{songrit(:authenticate)}".to_sym, :except=>[:index]
  before_filter :authenticate, :only=>[:chat]
  before_filter :post_log, :except=>[:index, :welcome, :manual, :contact, :download]
  skip_before_filter :chat_user_leave, :only=>[:chat]

  def index
    @announce= File.read("public/announce.txt") if File.exists?("public/announce.txt")
  end
  def announce_update
    File.open("public/announce.txt", "w") do |f|
      f.write(params[:announce])
    end
    redirect_to_root
  end
  def remove_chat_user
    Juggernaut.send_to_all("$('#{params[:login]}').remove()")
    render :text => "done"
  end
  def annouce_chat_user
    announce_user(params[:login])
  end
  def chat
    @login= params[:login] || "anonymous"
    if params[:login]
      @user= User.find_by_login @login
      chat_user= ChatUser.new(:login=>params[:login])
      if chat_user.save
        @list_all_user = true
        announce_user(@login) unless DLOC_SERVER
        @annouce= true
      end
    end
    if params[:embed]=='1'
      render :layout=>false
    end
  end
  def chat_broadcast
    @login= params[:login] || "anonymous"
    @user= User.find_by_login params[:login]
    unless params[:msg].blank?
      msg= params[:msg].dup
      Vulgar.all.each do |v|
        msg.gsub!(v.original,v.alternate)
      end
      Chat.create :user_id=>@user.id, :message=>msg, :message_original=>params[:msg],
        :ip=>request.env['REMOTE_ADDR']
      broadcast(msg)
    end
    render false
  end
  def pic
    @tcid_upload= TcidUpload.find params[:id]
    send_data @tcid_upload.content, :filename=>@tcid_upload.filename, :disposition=>'inline'
  end
  def welcome
    @name = ''
    if params[:name]
      @name = params[:name]
    end
  end
  def login_tcid
    user_sso= http("#{songrit(:host_sso)}/main/info/#{params[:login]}?app=#{songrit(:tcid_appid)}")
    @user= XmlSimple.xml_in(user_sso, 'ForceArray'=>false)
    # check if user exist in our db
    user= User.find_by_login(@user['login'])
    if user.blank?
      # create new user
      user= User.new :login=>@user['login'], :lao_id=>@user['lao-id']['content'],
        :title=>@user['title'], :fname=>@user['fname'], :lname=>@user['lname'],
        :lao_code=>@user['lao-code'], :registration_code=>@user['registration-code'],
        :position=>@user['position'],:user_type=>@user['user_type'],
        :ip=>request.env["REMOTE_ADDR"], :email=>@user['email']
      user.save
      # send register email (Move back to tcid now)
      #Notifier.deliver_register_send(@user['email'])
      # @message = DlearnUtility.get_register_body
      #mail_body = render_to_string :action => "login_tcid", :template => "notifier/register_send", :layout => false
      #Mail.sendmail(DlearnUtility.get_system_email, @user['email'], DlearnUtility.get_register_subject, mail_body)
    end
    # set session[:user]
    session[:user_id]= user.id
    flash[:notice]= "ยินดีต้อนรับเข้าสู่ระบบศึกษาทางไกล สกถ."
    redirect_to :action=>"welcome"
  end
  def logout
#    session[:user]= nil
    reset_session
    redirect_to "#{songrit(:host_sso)}/main/logout?callback=#{songrit(:host)}"
  end
  
  def change_role
    search= params[:search]||""
    @users = User.paginate(:all, :page => params[:page], :conditions=>"login LIKE '%#{search}%'", :per_page => 25)
  end
  
  def assign_role
    #new_roles = params[:role][:selected_field].join(",") if params[:role][:selected_field] != nil
#    debugger
    roles_array = []
    roles_array.push(params[:Admin]) if params[:Admin]!=nil
    roles_array.push(params[:Teacher]) if params[:Teacher]!=nil
    roles_array.push(params[:Dloc]) if params[:Dloc]!=nil
    new_roles = roles_array.join(",")
    @row_indicator_id = params[:row_id]
    @user = User.find(params[:user_id])
    @user.update_attribute("role", new_roles)
#    @user.role = new_roles
#    @user.nid = "9999999999999" if @user.nid==nil
#    @user.email = "none@none.none" if @user.email==nil
#    @user.fname = "none" if @user.fname==nil
#    @user.lname = "none" if @user.lname==nil
#    @user.save
    render :layout => false
  end
  
  def change_password_result
    flash[:notice] = params[:msg]
  end
  
  def edit_profile
    # update user
    user_sso= http("#{songrit(:host_sso)}/main/info/#{params[:login]}?app=#{songrit(:tcid_appid)}")
    @user= XmlSimple.xml_in(user_sso, 'ForceArray'=>false)
    user = User.update(session[:user_id], {:login=>@user['login'], :lao_id=>@user['lao-id']['content'],
      :title=>@user['title'], :fname=>@user['fname'], :lname=>@user['lname'],
      :lao_code=>@user['lao-code'], :registration_code=>@user['registration-code'],
      :position=>@user['position'],:user_type=>@user['user_type'],
      :ip=>request.env["REMOTE_ADDR"], :email=>@user['email']})
    # set session[:user]
    session[:user_id]= user.id
    flash[:notice] = params[:msg]
  end

  def show_comments
    @id = params[:id]
    render :action=>"show_comments", :layout=>false
  end
  
end
